<template>
  <div class="home_container">
    <div class="home_header">
      <img src="@/assets/images/time.png" alt="">
      <RunTime />
    </div>
    <div class="home_con">
      <div class="home_con_left">
        <!--当月战报-->
        <div class="home_con_left_top">
          <div class="home_con_left_top_icon">
            <span>当月战报</span>
            <div class="home_con_left_top_icon_title_icon"></div>
          </div>
          <ul class="home_con_left_top_con">
            <li>
              <img src="@/assets/images/top3.png" alt="">
              <div class="home_con_left_top_con_count">
                <span>成交量(单位:笔)</span>
                <span>{{formatNumber(monthReportData?.total) || 0}}</span>
              </div>
            </li>
            <li>
              <img src="@/assets/images/top4.png" alt="">
              <div class="home_con_left_top_con_count">
                <span>成交金额(单位:元)</span>
                <span>{{formatNumber(monthReportData?.totalAmount) || 0}}</span>
              </div>
            </li>
            <li>
              <img src="@/assets/images/top5.png" alt="">
              <div class="home_con_left_top_con_count">
                <span>到账金额(单位:元)</span>
                <span>{{formatNumber(monthReportData?.paymentsAmount) || 0}}</span>
              </div>
            </li>
          </ul>
        </div>
        <!--当月销售业绩排名-->
        <div class="home_con_left_top home_con_left_top_table">
          <div class="home_con_left_top_icon">
            <span>当月销售业绩排名</span>
            <div class="home_con_left_top_icon_title_icon"></div>
          </div>
          <div class="home_con_left_top_table_con">
            <div class="table-container">
              <!-- 固定的前三条数据 -->
              <el-table
                  :data="fixedData1"
                  style="width: 100%"
                  stripe
                  class="custom-table fixed-table-container">
                <el-table-column prop="sort" label="序号" width="70">
                  <template #default="scope">
                    <div class="el-table__icon"></div>
                  </template>
                </el-table-column>
                <el-table-column prop="nikeName" label="小组(城市)" show-overflow-tooltip>
                  <template #default="scope">
                    <div style="display: flex;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;">
                      {{scope?.row?.nikeName ?? ''}}
                      <div v-if="scope?.row?.cityName">（{{scope?.row?.cityName ?? ''}}）</div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="receivedCount" label="成交数" width="75">
                  <template #default="scope">
                    {{formatNumber(scope.row.receivedCount) || 0}}
                  </template>
                </el-table-column>
                <el-table-column prop="totalAmount" label="成交金额" width="100">
                  <template #default="scope">
                    {{formatNumber(scope.row.totalAmount) || 0}}
                  </template>
                </el-table-column>
                <el-table-column prop="receivedAmount" label="到账金额" width="100">
                  <template #default="scope">
                    {{formatNumber(scope.row.receivedAmount) || 0}}
                  </template>
                </el-table-column>
                <el-table-column prop="allAmount" label="总到账金额" width="110">
                  <template #default="scope">
                    {{formatNumber(scope.row.allAmount) || 0}}
                  </template>
                </el-table-column>
              </el-table>

              <!-- 滚动的数据 -->
              <el-table
                  :data="scrollData1"
                  stripe
                  class="custom-table scroll-table-container"
                  style="width: 100%; overflow: hidden; border-bottom-left-radius: 10px;"
              >
                <el-table-column prop="sort" width="70" />
                <el-table-column prop="nikeName" show-overflow-tooltip>
                  <template #default="scope">
                    <div style="display: flex;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;">
                      {{scope?.row?.nikeName ?? ''}}
                      <div v-if="scope?.row?.cityName">（{{scope?.row?.cityName ?? ''}}）</div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="receivedCount" width="75">
                  <template #default="scope">
                    {{formatNumber(scope.row.receivedCount) || 0}}
                  </template>
                </el-table-column>
                <el-table-column prop="totalAmount" width="100">
                  <template #default="scope">
                    {{formatNumber(scope.row.totalAmount) || 0}}
                  </template>
                </el-table-column>
                <el-table-column prop="receivedAmount" width="100">
                  <template #default="scope">
                    {{formatNumber(scope.row.receivedAmount) || 0}}
                  </template>
                </el-table-column>
                <el-table-column prop="allAmount" width="110">
                  <template #default="scope">
                    {{formatNumber(scope.row.allAmount) || 0}}
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div class="table-container">
              <!-- 固定的前三条数据 -->
              <el-table
                  :data="fixedData2"
                  style="width: 100%"
                  stripe
                  class="custom-table fixed-table-container">
                  <el-table-column prop="sort" label="序号" width="70">
                    <template #default="scope">
                      <div class="el-table__icon"></div>
                    </template>
                  </el-table-column>
                <el-table-column prop="nikeName" label="姓名(城市)" show-overflow-tooltip>
                  <template #default="scope">
                    <div style="display: flex;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;">
                      {{scope?.row?.nikeName ?? ''}}
                      <div v-if="scope?.row?.cityName">（{{scope?.row?.cityName ?? ''}}）</div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="receivedCount" label="成交数" width="75">
                  <template #default="scope">
                    {{formatNumber(scope.row.receivedCount) || 0}}
                  </template>
                </el-table-column>
                <el-table-column prop="totalAmount" label="成交金额" width="100">
                  <template #default="scope">
                    {{formatNumber(scope.row.totalAmount) || 0}}
                  </template>
                </el-table-column>
                <el-table-column prop="receivedAmount" label="到账金额" width="100">
                  <template #default="scope">
                    {{formatNumber(scope.row.receivedAmount) || 0}}
                  </template>
                </el-table-column>
                <el-table-column prop="allAmount" label="总到账金额" width="110">
                  <template #default="scope">
                    {{formatNumber(scope.row.allAmount) || 0}}
                  </template>
                </el-table-column>
              </el-table>
              <!-- 滚动的数据 -->
              <el-table
                  :data="scrollData2"
                  stripe
                  class="custom-table scroll-table-container"
                  style="width: 100%; overflow: hidden; border-bottom-right-radius: 10px;">
                <el-table-column prop="sort" width="70" />
                <el-table-column prop="nikeName" show-overflow-tooltip>
                  <template #default="scope">
                    <div style="display: flex;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;">
                      {{scope?.row?.nikeName ?? ''}}
                      <div v-if="scope?.row?.cityName">（{{scope?.row?.cityName ?? ''}}）</div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="receivedCount" width="75">
                  <template #default="scope">
                    {{formatNumber(scope.row.receivedCount) || 0}}
                  </template>
                </el-table-column>
                <el-table-column prop="totalAmount" width="100">
                  <template #default="scope">
                    {{formatNumber(scope.row.totalAmount) || 0}}
                  </template>
                </el-table-column>
                <el-table-column prop="receivedAmount" width="100">
                  <template #default="scope">
                    {{formatNumber(scope.row.receivedAmount) || 0}}
                  </template>
                </el-table-column>
                <el-table-column prop="allAmount" width="110">
                  <template #default="scope">
                    {{formatNumber(scope.row.allAmount) || 0}}
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>
      </div>

      <div class="home_con_right home_con_left">
        <!--第一季度销售业绩排名-->
        <div class="home_con_left_top home_con_left_top_table table_right_con">
          <div class="home_con_left_top_icon">
            <span>{{new Date().getFullYear()}}年第{{currentQuarter}}季度销售业绩排名</span>
            <div class="home_con_left_top_icon_title_icon"></div>
          </div>
          <div class="home_con_left_top_table_con">
            <div class="table-container">
              <el-table
                  :data="quarterDepData"
                  style="width: 100%"
                  stripe
                  class="custom-table">
                <el-table-column prop="name" label="小组排名" show-overflow-tooltip>
                  <template #default="scope">
                    <div class="el-table__icon"></div>
                    <span>{{ scope.row.nikeName }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="receivedCount" label="成交数">
                  <template #default="scope">
                    {{formatNumber(scope.row.receivedCount) || 0}}
                  </template>
                </el-table-column>
                <el-table-column prop="totalAmount" label="成交金额">
                  <template #default="scope">
                    {{formatNumber(scope.row.totalAmount) || 0}}
                  </template>
                </el-table-column>
                <el-table-column prop="receivedAmount" label="到账金额">
                  <template #default="scope">
                    {{formatNumber(scope.row.receivedAmount) || 0}}
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div class="table-container">
              <el-table
                  :data="quarterUserData"
                  style="width: 100%"
                  stripe
                  class="custom-table">
                <el-table-column prop="name" label="个人排名" width="110" show-overflow-tooltip>
                  <template #default="scope">
                    <div class="el-table__icon"></div>
                    <span>{{ scope.row.nikeName }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="receivedCount" label="成交数">
                  <template #default="scope">
                    {{formatNumber(scope.row.receivedCount) || 0}}
                  </template>
                </el-table-column>
                <el-table-column prop="totalAmount" label="成交金额">
                  <template #default="scope">
                    {{formatNumber(scope.row.totalAmount) || 0}}
                  </template>
                </el-table-column>
                <el-table-column prop="receivedAmount" label="到账金额">
                  <template #default="scope">
                    {{formatNumber(scope.row.receivedAmount) || 0}}
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>
        <!--2024年5月销售业绩排名-->
        <div class="home_con_left_top home_con_left_top_table table_right_con">
          <div class="home_con_left_top_icon">
            <span>{{new Date().getFullYear()}}年{{new Date().getMonth()}}月销售业绩排名</span>
            <div class="home_con_left_top_icon_title_icon"></div>
          </div>
          <div class="home_con_left_top_table_con">
            <div class="table-container">
              <el-table
                  :data="lastMonthDepData"
                  style="width: 100%"
                  stripe
                  class="custom-table">
                <el-table-column prop="name" label="小组排名" width="110" show-overflow-tooltip>
                  <template #default="scope">
                    <div class="el-table__icon"></div>
                    <span>{{ scope.row.nikeName }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="receivedCount" label="成交数">
                  <template #default="scope">
                    {{formatNumber(scope.row.receivedCount) || 0}}
                  </template>
                </el-table-column>
                <el-table-column prop="totalAmount" label="成交金额">
                  <template #default="scope">
                    {{formatNumber(scope.row.totalAmount) || 0}}
                  </template>
                </el-table-column>
                <el-table-column prop="receivedAmount" label="到账金额">
                  <template #default="scope">
                    {{formatNumber(scope.row.receivedAmount) || 0}}
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div class="table-container">
              <el-table
                  :data="lastMonthUserData"
                  style="width: 100%"
                  stripe
                  class="custom-table">
                <el-table-column prop="name" label="个人排名" width="110" show-overflow-tooltip>
                  <template #default="scope">
                    <div class="el-table__icon"></div>
                    <span>{{ scope.row.nikeName }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="receivedCount" label="成交数">
                  <template #default="scope">
                    {{formatNumber(scope.row.receivedCount) || 0}}
                  </template>
                </el-table-column>
                <el-table-column prop="totalAmount" label="成交金额">
                  <template #default="scope">
                    {{formatNumber(scope.row.totalAmount) || 0}}
                  </template>
                </el-table-column>
                <el-table-column prop="receivedAmount" label="到账金额">
                  <template #default="scope">
                    {{formatNumber(scope.row.receivedAmount) || 0}}
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>
        <!--第一季度销售业绩排名-->
        <div class="home_con_left_top home_con_left_top_table table_right_con">
          <div class="home_con_left_top_icon">
            <span>{{new Date().getFullYear()}}年{{new Date().getMonth() + 1}}月第{{currentWeekOfMonth}}周销售业绩排名</span>
            <div class="home_con_left_top_icon_title_icon"></div>
          </div>
          <div class="home_con_left_top_table_con">
            <div class="table-container">
              <el-table
                  :data="weekDepData"
                  style="width: 100%"
                  stripe
                  class="custom-table">
                  <el-table-column prop="name" label="小组排名" width="110" show-overflow-tooltip>
                    <template #default="scope">
                      <div class="el-table__icon"></div>
                      <span>{{ scope.row.nikeName }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="receivedCount" label="成交数">
                  <template #default="scope">
                    {{formatNumber(scope.row.receivedCount) || 0}}
                  </template>
                </el-table-column>
                <el-table-column prop="totalAmount" label="成交金额">
                  <template #default="scope">
                    {{formatNumber(scope.row.totalAmount) || 0}}
                  </template>
                </el-table-column>
                <el-table-column prop="receivedAmount" label="到账金额">
                  <template #default="scope">
                    {{formatNumber(scope.row.receivedAmount) || 0}}
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div class="table-container">
              <el-table
                  :data="weekUserData"
                  style="width: 100%"
                  stripe
                  class="custom-table">
                <el-table-column prop="name" label="个人排名" width="110" show-overflow-tooltip>
                  <template #default="scope">
                    <div class="el-table__icon"></div>
                    <span>{{ scope.row.nikeName }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="receivedCount" label="成交数">
                  <template #default="scope">
                    {{formatNumber(scope.row.receivedCount) || 0}}
                  </template>
                </el-table-column>
                <el-table-column prop="totalAmount" label="成交金额">
                  <template #default="scope">
                    {{formatNumber(scope.row.totalAmount) || 0}}
                  </template>
                </el-table-column>
                <el-table-column prop="receivedAmount" label="到账金额">
                  <template #default="scope">
                    {{formatNumber(scope.row.receivedAmount) || 0}}
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>
        <!--全年退费排名-->
        <div class="home_con_left_top home_con_left_top_table table_right_con">
          <div class="home_con_left_top_icon">
            <span>{{new Date().getFullYear()}}年全年退费排名</span>
            <div class="home_con_left_top_icon_title_icon"></div>
          </div>
          <div class="home_con_left_top_table_con">
            <div class="table-container">
              <el-table
                  :data="monthRefUserTopData"
                  style="width: 100%"
                  stripe
                  class="custom-table">
                <el-table-column prop="name" label="小组排名" show-overflow-tooltip >
                  <template #default="scope">
                    <div class="el-table__icon"></div>
                    <span>{{ scope.row.nikeName }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="receivedCount" label="退费数">
                  <template #default="scope">
                    {{formatNumber(scope.row.receivedCount) || 0}}
                  </template>
                </el-table-column>
                <el-table-column prop="totalAmount" label="退费金额">
                  <template #default="scope">
                    {{formatNumber(scope.row.totalAmount) || 0}}
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div class="table-container">
              <el-table
                  :data="monthRefDepTopData"
                  style="width: 100%"
                  stripe
                  class="custom-table">
                <el-table-column prop="name" label="个人排名" show-overflow-tooltip>
                  <template #default="scope">
                    <div class="el-table__icon"></div>
                    <span>{{ scope.row.nikeName }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="receivedCount" label="退费数">
                  <template #default="scope">
                    {{formatNumber(scope.row.receivedCount) || 0}}
                  </template>
                </el-table-column>
                <el-table-column prop="totalAmount" label="退费金额">
                  <template #default="scope">
                    {{formatNumber(scope.row.totalAmount) || 0}}
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>
      </div>
    </div>
    <SpeechPopup
      :messages="broadcastData"
      :isShow="isShowPopup"
      @close="isShowPopup = false"
    />
<!--    <el-button id="btn" @click="btnClick">点我</el-button>-->
  </div>
</template>

<script setup lang="ts">
import autofit from 'autofit.js'
import {
  getCurrentInstance,
  onMounted,
  ref,
  Ref,
  onBeforeUnmount
} from 'vue';
import './index.less';
import RunTime from '@/components/RunningTime.vue';
import SpeechPopup from "@/pages/broadcast/SpeechPopup.vue";

interface IMonthReportData {
  total: number;
  paymentsAmount: number;
  totalAmount: number;
}

interface tableData {
  nikeName: string;
  totalAmount: number;
  receivedAmount: number;
  receivedCount: number;
  cityName: string;
  allAmount: number;
  sort?: number;
}

const { appContext } = getCurrentInstance()!;
const api = appContext.config.globalProperties.$api;
const monthReportData: Ref<IMonthReportData | null> = ref(null);

const isShowPopup = ref(false);


  const monthDepGroupData = ref([]);
  const monthUserGroupData = ref([]);
  const broadcastData = ref<string[]>([]);

  const quarterDepData = ref([]);
  const quarterUserData = ref([]);

  const lastMonthDepData = ref([]);
  const lastMonthUserData = ref([]);

  const weekDepData = ref([]);
  const weekUserData = ref([]);

  let mainInterId: ReturnType<typeof setInterval> | null = null;
  let tableIntervalId1: ReturnType<typeof setInterval> | null = null;
  let tableIntervalId2: ReturnType<typeof setInterval> | null = null;


  const monthRefDepTopData = ref([]);
  const monthRefUserTopData = ref([]);
  let fixedData1 = ref([]);
  let scrollData1 = ref([]);
  let fixedData2 = ref([]);
  let scrollData2 = ref([]);
  const currentQuarter = ref(0);
  const currentWeekOfMonth = ref(0);
  const currentQuarterDates = ref({ startDate: '', endDate: '' });
  const lastMonthDate = ref({ startDate: '', endDate: '' });
  const currentWeekDate = ref({ startDate: '', endDate: '' });

  onMounted(() => {
    autofit.init({
      el:".home_container", // 渲染的dom
      dw: 1920, // 设计稿的宽度，默认是 1920
      dh: 1080, // 设计稿的高度，默认是 1080
      resize: true // 是否监听resize事件，默认是 true
    })
    currentQuarter.value = getCurrentQuarter(); // 获取当前季度
    currentWeekOfMonth.value = getWeekOfMonth(new Date()); // 获取当月的当前周
    getCurrentQuarterDates(); // 获取当前季度开始结束时间
    lastMonthDate.value = getLastMonthDateRange(); // 获取上个月的开始和结束日期
    currentWeekDate.value = getWeekDates(); // 获取当周的开始和结束日期

  })
  // 超过10万格式化
  const formatNumber = (num: number | undefined) => {
    if (num && num >= 100000) {
      return (num / 10000).toFixed(1) + 'w';
    }
    return num;
  };
  // 获取当前季度
  const getCurrentQuarter = () => {
    const currentMonth = new Date().getMonth() + 1;
    return Math.ceil(currentMonth / 3);
  }
  // 获取当月的当前周
  const getWeekOfMonth = (date: Date) => {
    const startOfMonth = new Date(date.getFullYear(), date.getMonth(), 1);
    const dayOfMonth = date.getDate();
    const weekDayOfFirst = startOfMonth.getDay();
    return Math.ceil((dayOfMonth + weekDayOfFirst) / 7);
  }
  // 获取当前季度开始结束时间
  const getCurrentQuarterDates = () => {
    const now = new Date();
    const month = now.getMonth();
    let startMonth, endMonth;

    if (month < 3) {
      // First quarter
      startMonth = 0;
      endMonth = 2;
    } else if (month < 6) {
      // Second quarter
      startMonth = 3;
      endMonth = 5;
    } else if (month < 9) {
      // Third quarter
      startMonth = 6;
      endMonth = 8;
    } else {
      // Fourth quarter
      startMonth = 9;
      endMonth = 11;
    }

    const start = new Date(now.getFullYear(), startMonth, 1);
    const end = new Date(now.getFullYear(), endMonth + 1, 0);

    const formatDate = (date: Date) => {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    };

    currentQuarterDates.value = {
      startDate: formatDate(start), // Format as YYYY-MM-DD
      endDate: formatDate(end) // Format as YYYY-MM-DD
    };
  };
  // 获取上个月的开始和结束日期的函数
  const getLastMonthDateRange = () => {
    const now = new Date();
    const start = new Date(now.getFullYear(), now.getMonth() - 1, 1);
    const end = new Date(now.getFullYear(), now.getMonth(), 0);

    const format = (date: Date) => {
      const year = date.getFullYear();
      const month = ('0' + (date.getMonth() + 1)).slice(-2);
      const day = ('0' + date.getDate()).slice(-2);
      return `${year}-${month}-${day}`;
    };
    return {
      startDate: format(start),
      endDate: format(end)
    }
  };
  const getWeekDates = () => {
    const currentDate = new Date();
    const firstDayOfWeek = new Date(currentDate.setDate(currentDate.getDate() - currentDate.getDay() + 1));
    const lastDayOfWeek = new Date(currentDate.setDate(currentDate.getDate() - currentDate.getDay() + 7));

    const formatDate = (date: Date) => {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    };

    return {
      startDate: formatDate(firstDayOfWeek),
      endDate: formatDate(lastDayOfWeek)
    };
  }
  // 获取当月战报
  const getMonthReport = async () => {
    try {
      const { data } = await api.get('/largeScreen/getMonthlyBattleReport');
      if (data.code === 0) {
        monthReportData.value = data.data;
        console.log('当月战报', monthReportData.value);
      }
    } catch (error) {
      console.error('当月战报error：', error);
    }
  }
// 获取播报信息
const getBroadcast = async () => {
  try {
    const { data } = await api.get('/largeScreen/getBroadcast');
    if (data.code === 0) {
      const broadcasts: string[] = ([]);
      for (const item of data.data) {
        let iitem = `恭喜${item.name}成单，成交金额${item.amount}元`;
        broadcasts.push(iitem);
        await updateBroadcast(item.receivedId);
      }
      // 打开播报弹窗
      if (broadcasts.length > 0) {
        broadcastData.value = broadcasts;
        isShowPopup.value = true;
      }
      console.log('播报信息', broadcastData.value);
    }
  } catch (error) {
    console.error('播报信息error：', error);
  }
}
// 更新播报信息
const updateBroadcast = async (receivedId: number) => {
    try {
      const { data } = await api.post(`/largeScreen/saveBroadcase?receivedId=${receivedId}`);
      if (data.code === 0) {
        console.log('更新播报信息成功');
      }
    } catch (error) {
      console.error('更新播报信息error：', error);
    }
}
  // 获取当月部门分组
  const getMonthDepGroup = async () => {
    try {
      const { data } = await api.get('/largeScreen/getMonthlyDepGroup');
      if (data.code === 0) {
        monthDepGroupData.value = data?.data?.map((item: tableData, index: number) => {
          return {...item, sort: formatIndex(index) }
        })!
        // 固定前三条数据
        fixedData1.value = monthDepGroupData.value.slice(0, 3);
        scrollData1.value = monthDepGroupData.value.slice(3);
        startTableScroll();  // 在数据更新后重新启动滚动

        console.log('当月部门分组', monthDepGroupData?.value);
      }
    } catch (error) {
      console.error('当月部门分组error', error);
    }
  }
  const startTableScroll = () => {
    // 清除之前的定时器
    if (tableIntervalId1) clearInterval(tableIntervalId1);
    if (tableIntervalId2) clearInterval(tableIntervalId2);

    // 滚动数据
    if (scrollData1.value.length > 10) {
      tableIntervalId1 = setInterval(() => {
        scrollData1.value.push(scrollData1.value.shift()!);
      }, 2000);
    }
    if (scrollData2.value.length > 10) {
      tableIntervalId2 = setInterval(() => {
        scrollData2.value.push(scrollData2.value.shift()!);
      }, 2000);
    }
  }
  // 获取当月人员分组
  const getMonthUserGroup = async () => {
    try {
      const { data } = await api.get('/largeScreen/getMonthlyUserGroup');
      if (data.code === 0) {
        monthUserGroupData.value = data?.data?.map((item: tableData, index: number) => {
          return {...item, sort: formatIndex(index) }
        })!
        // 固定前三条数据
        fixedData2.value = monthUserGroupData.value.slice(0, 3);
        scrollData2.value = monthUserGroupData.value.slice(3);
        startTableScroll();  // 在数据更新后重新启动滚动

        console.log('当月人员分组', monthUserGroupData.value);
      }
    } catch (error) {
      console.error('当月人员分组error', error);
    }
  }
  // 获取部门分组top3
  const getMonthDepTop3 = async (startDate: string, endDate: string, title: string) => {
    try {
      const { data } = await api.get(`/largeScreen/getMonthlyDepGroupTop3?startDate=${startDate}&endDate=${endDate}`);
      if (data.code === 0) {
        console.log(title, data?.data)
        return data?.data;
      }
    } catch (error) {
      console.error(error);
    }
  }
  // 获取人员分组top3
  const getMonthUserTop3 = async (startDate: string, endDate: string, title: string) => {
    try {
      const { data } = await api.get(`/largeScreen/getMonthlyUserGroupTop3?startDate=${startDate}&endDate=${endDate}`);
      if (data.code === 0) {
        console.log(title, data?.data)
        return data?.data;
      }
    } catch (error) {
      console.error(error);
    }
  }
  // 获取当前年退费部门分组
  const getRefDepGroup = async () => {
    try {
      const { data } = await api.get('/largeScreen/getRefundsUserGroup');
      if (data.code === 0) {
        monthRefDepTopData.value = data?.data;
        console.log('当前年退费部门分组', monthRefDepTopData.value);
      }
    } catch (error) {
      console.error(error);
    }
  }
  // 获取当前年退费个人分组
  const getRefUserGroup = async () => {
    try {
      const { data } = await api.get('/largeScreen/getRefundsDepGroup');
      if (data.code === 0) {
        monthRefUserTopData.value = data?.data;
        console.log('当前年退费个人分组', monthRefUserTopData.value);
      }
    } catch (error) {
      console.error(error);
    }
  }
  // 格式化序号
  const formatIndex = (index: number) => {
    return (index + 1).toString().padStart(2, '0');
  };

const startRequestLoop = async() => {
  let minuteCounter = 0;
  mainInterId = setInterval(async () => {
    minuteCounter++;
    if (minuteCounter % 6 === 0) {
      await getMonthReport(); // 当月战报
      quarterDepData.value  = await getMonthDepTop3(currentQuarterDates.value.startDate, currentQuarterDates.value.endDate, '季度部门top3'); // 季度部门top3
      quarterUserData.value = await getMonthUserTop3(currentQuarterDates.value.startDate, currentQuarterDates.value.endDate, '季度人员top3'); // 季度人员top3

      quarterDepData.value  = await getMonthDepTop3(lastMonthDate.value.startDate, lastMonthDate.value.endDate, '上月部门top3'); // 上月部门top3
      quarterUserData.value = await getMonthUserTop3(lastMonthDate.value.startDate, lastMonthDate.value.endDate, '上月人员top3'); // 上月人员top3

      quarterDepData.value  = await getMonthDepTop3(currentWeekDate.value.startDate, currentWeekDate.value.endDate, '本周部门top3'); // 本周部门top3
      quarterUserData.value = await getMonthUserTop3(currentWeekDate.value.startDate, currentWeekDate.value.endDate, '本周人员top3'); // 本周人员top3

      await getRefDepGroup(); // 当前年退费部门分组
      await getRefUserGroup(); // 当前年退费人员分组
    } else if (minuteCounter % 2 === 0) {
        await getBroadcast(); // 播报信息
    } else {
      await getMonthDepGroup(); // 当月部门分组
      await getMonthUserGroup(); // 当月人员分组
    }
  }, 60000); // 每分钟执行一次
};

  onMounted(async() => {
    // 初始化数据
    await getMonthReport(); // 当月战报
    await getBroadcast(); // 播报信息
    await getMonthDepGroup(); // 当月部门分组
    await getMonthUserGroup(); // 当月人员分组
    quarterDepData.value  = await getMonthDepTop3(currentQuarterDates.value.startDate, currentQuarterDates.value.endDate, '季度部门top3'); // 季度部门top3
    quarterUserData.value = await getMonthUserTop3(currentQuarterDates.value.startDate, currentQuarterDates.value.endDate, '季度人员top3'); // 季度人员top3
    lastMonthDepData.value  = await getMonthDepTop3(lastMonthDate.value.startDate, lastMonthDate.value.endDate, '上月部门top3'); // 上月部门top3
    lastMonthUserData.value = await getMonthUserTop3(lastMonthDate.value.startDate, lastMonthDate.value.endDate, '上月人员top3'); // 上月人员top3
    weekDepData.value  = await getMonthDepTop3(currentWeekDate.value.startDate, currentWeekDate.value.endDate, '本周部门top3'); // 本周部门top3
    weekUserData.value = await getMonthUserTop3(currentWeekDate.value.startDate, currentWeekDate.value.endDate, '本周人员top3'); // 本周人员top3
    await getRefDepGroup(); // 当前年退费部门分组
    await getRefUserGroup(); // 当前年退费人员分组
    // 启动循环
    await startRequestLoop();
  });
  onBeforeUnmount(() => {
    // 组件卸载时清除interval
    if (mainInterId) clearInterval(mainInterId);
    if (tableIntervalId1) clearInterval(tableIntervalId1);
    if (tableIntervalId2) clearInterval(tableIntervalId2);
  });

</script>